package sg.edu.nus.iss.jass.gui;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;

import sg.edu.nus.iss.jass.constant.ErrorConstants;
import sg.edu.nus.iss.jass.controller.JobSeekerController;
import sg.edu.nus.iss.jass.dto.JobSeeker;
import sg.edu.nus.iss.jass.dto.Skill;
import sg.edu.nus.iss.jass.dto.SkillReference;
import sg.edu.nus.iss.jass.exception.ValidationException;
import sg.edu.nus.iss.jass.gui.component.ValidateJTextField;
import sg.edu.nus.iss.jass.util.Util;
import sg.edu.nus.iss.jass.validation.ValidationRule;

public class JobSeekerFormPanel extends FormPanel {

	/**
	 * <h5>JobSeekerFormPanel to load the form for JobSSeeker Registration</h5>
	 * 
	 * @author Kafoor Sammil
	 * 
	 */
	private static final long serialVersionUID = -8594982019088544544L;

	private JLabel nameLbl;
	private JLabel telNoLbl;
	private JLabel emailLbl;
	private JLabel userIdLbl;
	private JLabel addressLbl;
	private JLabel skillLbl;

	private ValidateJTextField nameTxtField;
	private ValidateJTextField telNoTxtField;
	private ValidateJTextField emailTxtField;
	private ValidateJTextField userIdTxtField;
	private ValidateJTextField addressTxtField;;

	private JPanel skillsPanel;

	private JobSeeker jobSeeker = null;
	private JobSeekerController jobSeekerController = null;
	private List<SkillReference> skillsRefList = null;

	private final int NO_OF_SKILLS_ROWS = 5;
	String skills[] = { "JAVA", ".NET", "TIBCO" };
	String skillRefIds[] = null;

	String skillLevels[] = { "Select", "Beginner", "Intermediate", "Advanced" };

	JComboBox skillListCbx[] = null;
	JComboBox skillLevelCbx[] = null;
	ValidateJTextField skillExpTxtField[] = null;

	ArrayList<Skill> skillList = null;

	public JobSeekerFormPanel(MainFrame mainframe, ActionPanel actionPanel,
			HeaderPanel headerPanel) {
		super(mainframe, actionPanel, headerPanel);

	}

	public List<SkillReference> getSkillsList() {
		return skillsRefList;
	}

	public void setSkillsList(List<SkillReference> skillsList) {
		this.skillsRefList = skillsList;
	}

	@Override
	public void actionPerformed(ActionEvent e) {

		super.clearMsg();
		if (e.getActionCommand().equalsIgnoreCase("ADD")) {
			submit();
		} else if (e.getActionCommand().equalsIgnoreCase("Cancel")) {
			cancel();
		} else if (e.getActionCommand().equalsIgnoreCase("Reset")) {
			reset();
		}

	}

	void reset() {

		nameTxtField.setText("");
		telNoTxtField.setText("");
		emailTxtField.setText("");
		userIdTxtField.setText("");
		addressTxtField.setText("");

		this.remove(skillsPanel);
		skillsPanel = createSkillsPanel();
		skillsPanel.setBounds(10, 220, 650, 300);
		this.add(skillsPanel);
		this.validate();

	}

	public void displayCompletionMsg(String msg) {
		super.showMsg(msg, true);
	}

	public void displayErrorMsg(String msg) {
		super.showMsg(msg, false);
	}

	private void submit() {

		jobSeeker = new JobSeeker();
		try {
			jobSeeker.setName(nameTxtField.getValidatedText());
			jobSeeker.setUserId(userIdTxtField.getValidatedText());
			jobSeeker.setEmail(emailTxtField.getValidatedText());
			jobSeeker.setTelNo(telNoTxtField.getValidatedText());
			jobSeeker.setAddress(addressTxtField.getValidatedText());

			if (skillValidate()) {
				jobSeeker.setSkills(skillList);

			}

			jobSeekerController.processRegisterJobSeeker(jobSeeker);

		} catch (ValidationException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			super.showMsg(e.getMessage(), false);
		} catch (Exception e) {
			// e.printStackTrace();
			super.showMsg(e.getMessage(), false);
		}
	}

	private void cancel() {
		reset();
		super.showMsg("Action Cancelled", false);
	}

	private void initGUI() {
		this.nameLbl = new JLabel("Name:");
		nameLbl.setBounds(10, 10, 150, 25);
		this.add(this.nameLbl);

		this.userIdLbl = new JLabel("User ID:");
		userIdLbl.setBounds(10, 45, 150, 25);
		this.add(this.userIdLbl);

		this.emailLbl = new JLabel("Email:");
		emailLbl.setBounds(10, 80, 150, 25);
		this.add(this.emailLbl);

		this.telNoLbl = new JLabel("Telephone:");
		telNoLbl.setBounds(10, 115, 150, 25);
		this.add(this.telNoLbl);

		this.addressLbl = new JLabel("Address:");
		addressLbl.setBounds(10, 150, 150, 25);
		this.add(this.addressLbl);

		this.skillLbl = new JLabel("Skills Details");
		skillLbl.setBounds(10, 185, 150, 25);
		this.add(this.skillLbl);

		nameTxtField = new ValidateJTextField("Name", ValidationRule.NOT_NULL);
		nameTxtField.setBounds(150, 10, 250, 25);
		this.add(this.nameTxtField);

		userIdTxtField = new ValidateJTextField("User ID",
				ValidationRule.NOT_NULL);
		userIdTxtField.setBounds(150, 45, 250, 25);
		this.add(this.userIdTxtField);

		emailTxtField = new ValidateJTextField("Email",
				ValidationRule.NOT_NULL, ValidationRule.EMAIL);
		emailTxtField.setBounds(150, 80, 250, 25);
		this.add(this.emailTxtField);

		telNoTxtField = new ValidateJTextField("Telephone",
				ValidationRule.NUMERIC);
		telNoTxtField.setBounds(150, 115, 250, 25);
		this.add(this.telNoTxtField);

		addressTxtField = new ValidateJTextField("Address",
				ValidationRule.NOT_NULL);
		addressTxtField.setBounds(150, 150, 250, 25);
		this.add(this.addressTxtField);

		skills = getSkillReferenceArray();
		skillsPanel = createSkillsPanel();
		skillsPanel.setBounds(10, 220, 650, 300);
		this.add(skillsPanel);
	}

	@Override
	public void show() {

		initGUI();
		addFormPanel();

	}

	private String[] getSkillReferenceArray() {

		if (skillsRefList != null && skillsRefList.size() > 0) {
			skills = new String[skillsRefList.size() + 1];
			skillRefIds = new String[skillsRefList.size() + 1];
			int i = 0;

			skills[i] = "Select";
			skillRefIds[i] = "";
			i++;
			Iterator<SkillReference> it = skillsRefList.iterator();

			while (it.hasNext()) {
				SkillReference skillref = (SkillReference) it.next();
				skills[i] = skillref.getName();
				skillRefIds[i] = skillref.getId();
				i++;
			}
		}

		return skills;
	}

	private JPanel createSkillsPanel() {

		JPanel pane = new JPanel(new GridLayout());
		pane.setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();
		c.fill = GridBagConstraints.HORIZONTAL;
		c.weightx = 1.5;
		c.weighty = 0.5;
		c.insets = new Insets(5, 5, 5, 5);
		c.ipady = 10;

		c.gridx = 0;
		c.gridy = 0;
		pane.add(new JLabel("Skill"), c);

		c.gridx = 1;
		c.gridy = 0;
		pane.add(new JLabel("Skill Level"), c);

		c.gridx = 2;
		c.gridy = 0;
		pane.add(new JLabel("Years Of Experience"), c);

		skillListCbx = new JComboBox[NO_OF_SKILLS_ROWS];
		int y = 1;
		for (int i = 0; i < NO_OF_SKILLS_ROWS; i++) {
			skillListCbx[i] = new JComboBox(skills);
			c.gridx = 0;
			c.gridy = y++;
			pane.add(skillListCbx[i], c);
		}

		skillLevelCbx = new JComboBox[NO_OF_SKILLS_ROWS];
		y = 1;
		for (int i = 0; i < NO_OF_SKILLS_ROWS; i++) {
			skillLevelCbx[i] = new JComboBox(skillLevels);
			c.gridx = 1;
			c.gridy = y++;
			pane.add(skillLevelCbx[i], c);
		}

		skillExpTxtField = new ValidateJTextField[NO_OF_SKILLS_ROWS];
		y = 1;
		for (int i = 0; i < NO_OF_SKILLS_ROWS; i++) {
			skillExpTxtField[i] = new ValidateJTextField("Years Of Experience",
					ValidationRule.NUMERIC);
			c.ipady = 10;
			c.gridx = 2;
			c.gridy = y++;
			pane.add(skillExpTxtField[i], c);
		}

		return pane;
	}

	@SuppressWarnings("unused")
	private boolean skillValidate() throws ValidationException {

		HashMap<String, Skill> exisitingSkills = new HashMap<String, Skill>();

		skillList = new ArrayList<Skill>();
		for (int i = 0; i < NO_OF_SKILLS_ROWS; i++) {

			Skill skill = null;
			if (skillListCbx[i] != null
					&& skillListCbx[i].getSelectedItem() != null) {

				String tmpSkillName = skillListCbx[i].getSelectedItem()
						.toString();

				if (!tmpSkillName.equals("Select")) {

					int tmpSkillIndex = skillListCbx[i].getSelectedIndex();
					String tmpSkillRefId = skillRefIds[tmpSkillIndex]; 

					String tmpSkillLevel = skillLevelCbx[i].getSelectedItem()
							.toString();

					if (tmpSkillLevel.equals("Select")) {
						throw new ValidationException(
								"Please Select Skill Level");
					}

					String tmpSkillExp = skillExpTxtField[i].getValidatedText();
					if (tmpSkillExp.trim().length() == 0) {
						throw new ValidationException(
								"Please enter Years Of Experience");
					}

					skill = new Skill();
					skill.setSkillRefId(tmpSkillRefId);
					skill.setLvl(Util.getSkillLevelCode(tmpSkillLevel));
					skill.setYearOfExp(Integer.parseInt(tmpSkillExp));

					if (!exisitingSkills.containsKey(tmpSkillName)) {
						skillList.add(skill);
						exisitingSkills.put(tmpSkillName, skill);
					} else {
						throw new ValidationException("Duplicate Skills");
					}

				} else if (!skillLevelCbx[i].getSelectedItem().equals("Select")
						|| skillExpTxtField[i].getText().trim().length() > 0) {

					throw new ValidationException("Incomplete Skill Details ");
				}
			}
		}
		
		if(skillList.isEmpty()) {
			throw new ValidationException(ErrorConstants.ERROR_NO_SKILL_SPECIFIED);
		}
		return true;

	}

	public void setJobSeekerController(JobSeekerController jobSeekerController) {
		this.jobSeekerController = jobSeekerController;

	}

}
